<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>Banner管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 添加 -->
    <el-form :inline="true" class="user-search">
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addBannerVisible=true">添加首页Banner</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="bannerList" highlight-current-row border element-loading-text="拼命加载中"
              style="width: 100%;text-align: center">
      <el-table-column sortable prop="imgUrl" label="背景图片" width="1000" align="center">
        <template slot-scope="scope">
          <el-image :src="scope.row.imgUrl" style="max-width: 800px;max-height: 500px"></el-image>
        </template>
      </el-table-column>
      <el-table-column sortable prop="status" label="Banner位置" width="120" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.status===1">首页</div>
          <div v-else>社交专区</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="100">
        <template slot-scope="scope">
          <el-popconfirm
            style="margin-left: 10px"
            confirm-button-text='已知晓'
            cancel-button-text='我点错了'
            icon="el-icon-info"
            icon-color="red"
            title="删除不可逆，请谨慎操作"
            @confirm="deleteBanner(scope.row.id)"
          >
            <el-button size="mini" type="danger" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--    增加Banner-->
    <el-dialog title="新增Banner" :visible.sync="addBannerVisible" width="60%">
      <el-form :inline="true" class="user-search" :model="bannerForm" :rules="bannerFormRules" ref="bannerForm">
        <el-form-item label="图片上传：" prop="bannerImg">
          <el-upload
            class="upload-demo"
            drag
            :limit="1"
            list-type="picture"
            accept="image/jpeg,image/gif,image/png"
            :on-exceed="bannerHeaderHandleExceed"
            :on-change="bannerHeaderHandleChange"
            :on-progress="bannerHeaderHandleProgress"
            :on-remove="bannerHeaderHandleRemove"
            :before-upload="beforeUploadBanner"
            :auto-upload="false"
            :file-list="bannerForm.bannerImg"
            action="https://jsonplaceholder.typicode.com/posts/"
            :http-request="uploadBanner"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="位置：">
          <el-select v-model="value" size="small">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div style="margin-top: 20px;text-align: right">
        <el-button size="small" type="primary" @click="uploadBanner" :loading="uploadLoading">上传</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "Banner",
    data() {
      return {
        addBannerVisible: false,
        bannerList: [],
        uploadSuccessImg: '',
        bannerForm: {
          bannerImg: null,
          bannerStatus: ''
        },
        options: [{
          value: '1',
          label: '首页'
        }, {
          value: '2',
          label: '社交专区'
        }],
        value: '1',
        bannerFormRules: {
          bannerImg: [
            {
              required: true,
              message: '图片不能为空',
              trigger: 'blur'
            }
          ],
        },
        uploadLoading: false,
      }
    },
    created() {
      this.getAllBanner();
    },
    methods: {
      bannerHeaderHandleExceed(file, fileList) {
        this.$message.info(`您已上传一张图片，如需修改请点击下方删除`)
      },
      bannerHeaderHandleChange(file, fileList) {
        if (fileList.length >= 2) {
          return;
        } else {
          this.bannerForm.bannerImg = file;
        }
      },
      //文件上传时调用
      bannerHeaderHandleProgress(file) {
        this.bannerForm.bannerImg = file;
      },
      //移除
      bannerHeaderHandleRemove(file, fileList) {
        this.bannerForm.bannerImg = null
      },
      //上传图片之前校验格式
      beforeUploadBanner(file) {
        let FileExt = file.name.replace(/.+\./, "");
        if (['jpg', 'png', 'bmp', 'jpeg', 'gif'].indexOf(FileExt.toLowerCase()) === -1) {
          this.$message({
            type: 'warning',
            message: '请上传后缀名为jpg/png/bmp/jpeg/gif格式文件！'
          });
          return false;
        } else {
          return true;
        }
      },
      //自定义上传方法
      uploadBanner() {
        this.uploadLoading = true;
        if (this.bannerForm.bannerImg == null) {
          this.$message.warning(`Banner图片为空`);
        } else {
          let formData = new FormData();
          formData.append('file', this.bannerForm.bannerImg.raw);
          this.$axios({
            method: 'post',
            url: '/upload/uploadBanner',
            headers: {
              'Content-Type': 'multipart/form-data',
              authentication: localStorage.getItem("adminToken")
            },
            data: formData
          }).then(res => {
            if (res.data.msgCode === '200') {
              this.uploadSuccessImg = res.data.data.fileName;
              this.$message.success('上传成功');
              this.submitBanner();
              this.uploadLoading = false;
            } else {
              this.$message.warning('上传失败');
            }
          })
        }
      },
      submitBanner() {
        this.$axios({
          method: 'post',
          url: '/musicControl/addBanner',
          data: {
            imgUrl: this.uploadSuccessImg,
            status: this.value
          },
          headers: {
            authentication: localStorage.getItem("adminToken")
          },
        }).then(res => {
          if (res.data.msgCode === '200') {
            this.$message.success('增加成功');
            this.getAllBanner();
          } else {
            this.$message.warning('增加失败');
          }
        })
      },
      //删除
      deleteBanner(index) {
        if (index === undefined) {
          this.$notify.info({
            title: '提示',
            message: '删除错误'
          });
        } else {
          this.$axios({
            method: 'post',
            url: '/musicControl/deleteBanner/' + index,
            headers: {
              authentication: localStorage.getItem("adminToken")
            },
          }).then(res => {
            if (res.data.msgCode === '200') {
              this.$message.success(res.data.msg);
            } else {
              this.$message.error(res.data.msg);
            }
            this.getAllBanner();
          })
        }
      },
      getAllBanner() {
        let status = null;
        this.$axios({
          method: 'get',
          url: '/walking/getHeaderImg/' + status
        }).then(res => {
          this.bannerList = res.data.data.imgList;
        })
      }
    }
  }
</script>

<style scoped>
  .user-search {
    margin-top: 20px;
  }
</style>
